package dk.pekilidi.dod.util;

/**
 * User: mpeki
 * Date: 12-12-2007
 * Time: 22:26:39
 */
public class Dice {

    public static int roll(int numDice, int numEyes) {
        int result = 0;
        for(int i=0; i<numDice; i++){
            result += roll(numEyes);
        }
        return result;
    }

    public static int roll(int numEyes){
        return (int)((numEyes * Math.random()) + 1);
    }

    public static int parse(String dieRoll){
        boolean isNeg = false;
        int result = 0;
        if(dieRoll.startsWith("-")){
            isNeg=true;
            dieRoll = dieRoll.replaceFirst("\\-","");
        }
        String[] tSplit = dieRoll.split("T|t");
        if(tSplit.length != 2)
            throw new IllegalArgumentException("dieRoll String must contain T or t and be of the form eg. '1T6'");
        String[] opSplit = tSplit[1].split("\\+");
        if(opSplit.length == 2)
            result = roll(Integer.parseInt(tSplit[0]), Integer.parseInt(opSplit[0])) + Integer.parseInt(opSplit[1]);
        opSplit = tSplit[1].split("\\-");
        if(opSplit.length == 2)
            result = roll(Integer.parseInt(tSplit[0]), Integer.parseInt(opSplit[0])) - Integer.parseInt(opSplit[1]);
        else if (result == 0)
            result = roll(Integer.parseInt(tSplit[0]), Integer.parseInt(tSplit[1]));
        return isNeg ? - result : result;

    }
}
